package saucaca.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.MainActivity;
import lemon.kenhnhacvn.R;

import org.json.JSONException;

import saucaca.Adapter.ExpandableSongAdapter;
import saucaca.CustomView.CustomExpandableListView;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.AreaObject;
import saucaca.Object.HomeData;
import saucaca.Object.SongObject;
import saucaca.Util.TagName;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

public class BXHSongFragment extends Fragment implements saucaca.CustomView.CustomExpandableListView.IXListViewListener {
	public static final String TAG = OnlineSongList.class.getSimpleName();
	private final static String SONG = "1";
	ArrayList<SongObject> songs;
	String areaCode = "";
	String week = "0";
	String authorCode = "";
	String page = "0";
	String pageSize = "10";
	String[] array_spinner_Week;
	String[] array_spinner_Area;
	String btype = SONG;
	int xpage = 0;
	boolean loadingMore;
	MainActivity mActivity;
	private CustomExpandableListView expandListview;
	private View mView_EmptyLoading = null;
	private ProgressBar progressBar;
	ImageView imgEmpty, imgError;
	TextView txtStatus;
	boolean isFromMenu;
	TextView txtTitle;
	ExpandableSongAdapter adapter;
	private SwipeRefreshLayout mSwipeLayout;
	
	Spinner spinerWeekSong, spinerAreaSong;
	MyCustomAdapter adapterWeek, adapterArea;
	Calendar calendar;
	List<AreaObject> listArea;
	public BXHSongFragment() {
		new GetFromServices().execute("");
	}

	boolean checkString(String str) {
		if (str != null && !str.equals("")) {
			return true;
		} else
			return false;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mActivity = (MainActivity) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View android = inflater.inflate(R.layout.listview_expand, container, false);
		findviewByID(android);
		addheaderview();
		return android;
	}

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void findviewByID(View view) {
		expandListview = (CustomExpandableListView) view.findViewById(R.id.layoutlistview_ExpandListview);
		expandListview.setExpanded(true);
		mView_EmptyLoading = view.findViewById(R.id.empty_loading);
		expandListview.setEmptyView(mView_EmptyLoading);
		expandListview.setPullLoadEnable(true);
		expandListview.setXListViewListener(this);
		expandListview.startProgressBar();
		progressBar = (ProgressBar) mView_EmptyLoading.findViewById(R.id.empty_loading_progress);
		imgEmpty = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_NoItem);
		imgError = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_Error);
		txtStatus = (TextView) mView_EmptyLoading.findViewById(R.id.empty_loading_text);
		if(songs!=null)
			adapter = new ExpandableSongAdapter(mActivity, expandListview, songs);
		
		mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
		mSwipeLayout.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				xpage=0;
				loadingMore = false;
				expandListview.stopProgressBar();
				stop();
				new GetFromServices().execute("");
			}
		});
		mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
				android.R.color.holo_green_light, android.R.color.holo_orange_light,
				android.R.color.holo_red_light);
	}
	void addheaderview(){
		View view = getActivity().getLayoutInflater().inflate(R.layout.bxh_song_menu, null);
		spinerWeekSong = (Spinner) view.findViewById(R.id.BXH_spinner_weeksong);
		spinerAreaSong = (Spinner) view.findViewById(R.id.BXH_spinner_Areasong);
		expandListview.addHeaderView(view, null, false);
		
		calendar = Calendar.getInstance();
		int s = calendar.get(Calendar.WEEK_OF_YEAR);
		listArea = HomeData.homeListArea;
		array_spinner_Week = new String[s];
		for (int i = 0; i < s; i++) {
			array_spinner_Week[i] = "Tuần " + (s - i);
		}
		array_spinner_Area = new String[listArea.size()];
		for (int i = 0; i < listArea.size(); i++) {
			array_spinner_Area[i] = listArea.get(i).getTXNAME();
		}
		adapterWeek = new MyCustomAdapter(mActivity, R.layout.item_spinner, array_spinner_Week);
		adapterWeek.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		adapterArea = new MyCustomAdapter(mActivity, R.layout.item_spinner, array_spinner_Area);
		adapterArea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		spinerWeekSong.setAdapter(adapterWeek);
		spinerAreaSong.setAdapter(adapterArea);
	}

	class GetFromServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... param) {
			String str=null;
			page = Integer.toString(xpage);
			loadingMore = true;
			str = WServiceLib.Bxh(btype, areaCode, week, page, pageSize);
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					if (adapter == null) {
//						songs = JsonReader.readlistSongFromString(result, TagName.KEY_SONG);
						songs = JsonReader.readlistSongFromString(result, TagName.KEY_BXH);
//						listview_song.setAdapter(new ExpandableSongAdapter(mActivity, listview_song, listSongs));
						adapter = new ExpandableSongAdapter(mActivity, expandListview, songs,false,true);
						expandListview.setAdapter(adapter);
					} else {
						ArrayList<SongObject> listsong = JsonReader.readlistSongFromString(result, TagName.KEY_BXH);
						for (int i = 0; i < listsong.size(); i++) {
							boolean isAdded=false;
							for (int j = 0; j < songs.size(); j++) {
								if (songs.get(j).getSONG_ID().equals(listsong.get(i).getSONG_ID())) {
									isAdded=true;
								}
							}
							if(!isAdded)
								songs.add(listsong.get(i));
						}
						adapter.notifyDataSetChanged();
						adapter = new ExpandableSongAdapter(mActivity, expandListview, songs,false,true);
						expandListview.setAdapter(adapter);
					}
					if (songs.size() == 0) {
						progressBar.setVisibility(View.GONE);
						imgEmpty.setVisibility(View.VISIBLE);
						txtStatus.setText(mActivity.getResources().getString(R.string.no_item_song));
					}
					loadingMore = false;
					expandListview.stopProgressBar();
					if(mSwipeLayout.isRefreshing())
						mSwipeLayout.setRefreshing(false);
					stop();
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}

	}

	public void stop() {
		expandListview.stopRefresh();
		expandListview.stopLoadMore();
	}

	@Override
	public void onRefresh() {
		if (!loadingMore) {
			xpage += 1;
			new GetFromServices().execute("");
		} else
			stop();
	}

	@Override
	public void onLoadMore() {
		if (!loadingMore) {
			xpage += 1;
			new GetFromServices().execute("");
		} else
			stop();

	}
	public class MyCustomAdapter extends ArrayAdapter<String> {
		String[] objects;
		public MyCustomAdapter(Context context, int textViewResourceId, String[] objects) {
			super(context, textViewResourceId, objects);
			this.objects=objects;
		}

		@Override
		public View getDropDownView(int position, View convertView, ViewGroup parent) {
			return getCustomView(position, convertView, parent);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return getCustomView(position, convertView, parent);
		}

		public View getCustomView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = mActivity.getLayoutInflater();
			View row = inflater.inflate(R.layout.item_spinner, parent, false);
			TextView label = (TextView) row.findViewById(R.id.spinner_text);
			label.setText(objects[position]);
			return row;
		}
	}
}